// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------
module.exports = class extends think.cmswing.modIndex {
  /**
   * index action
   * @return {Promise} []
   * 封面入口
   */
  indexAction() {
    // console.log(this);
    // auto render template file index_index.html

    return this.body = '封面入口';
    // return this.display();
  }

  /**
   * 列表入口
   * @returns {*}
   */
  async listAction() {
    // 获取栏目信息
    let cate = this.m_cate;

    cate = think.extend({}, cate);
    // 栏目权限验证
    if (!await this.c_verify('visit')) {
      const error = this.controller('cmswing/error');
      return error.noAction('您所在的用户组,禁止访问本栏目！');
    }

    // 获取当前栏目的模型
    const model = this.mod;
    this.assign('model', model);

    // 获取当前分类的所有子栏目
    const subcate = await this.model('cmswing/category').get_sub_category(cate.id);
    subcate.push(cate.id);

    // 当前栏目列表每页行数
    const num = this.page_num();

    // 获取面包屑信息
    await this.breadcrumb();

    // 获取列表数据
    // 条件
    const map = {
      // 'category_id': ['IN', subcate]
    };
    // 排序
    let o = {};
    let selectMap = {};
    let order = this.modget(1) || 0;
    order = Number(order);
    switch (order) {
      case 1:
        o.popular_value = 'DESC';
        break;
      case 2:
        map.is_recommend = 1;
        o.id = 'DESC';
        break;
      case 3:
        map.answer_count = 0;
        o.id = 'DESC';
        break;
      default:
        o.id = 'DESC';
    }
    this.assign('order', order);
    const group_id = 0;
    // 获取分类信息
    const get = this.get('category') || 0;
    const query = get.split('-');
    let sortid = query[3] || 0;
    if (!think.isEmpty(sortid)) {
      // map.sort_id = sortid;
    }
    let sortarr = query[4] ? decodeURIComponent(query[4]) : null;
    let nsobj = {};
    let sort = await this.model('cmswing/category').get_category(cate.id, 'documentsorts');
    if (sort) {
      this.assign('sorturl', get.split('-')[4]);
      sort = JSON.parse(sort);
      if (sortid == 0) {
        sortid = sort.defaultshow;
      }
      const typevar = await this.model('typevar').where({sortid: sortid}).order('displayorder ASC').select();
      // console.log(typevar);

      for (const val of typevar) {
        val.option = await this.model('typeoption').where({optionid: val.optionid}).find();
        if (val.option.type == 'select' || val.option.type == 'radio') {
          if (!think.isEmpty(val.option.rules)) {
            val.option.rules = JSON.parse(val.option.rules);
            val.rules = parse_type_attr(val.option.rules.choices);
            selectMap[val.option.identifier] = parse_type_map(val.option.rules.choices);
            val.option.rules.choices = parse_config_attr(val.option.rules.choices);
            // console.log(val.rules);
          }
        } else if (val.option.type == 'checkbox') {
          if (!think.isEmpty(val.option.rules)) {
            val.option.rules = JSON.parse(val.option.rules);
            val.rules = parse_type_attr(val.option.rules.choices);
            selectMap = parse_type_map(val.option.rules.choices);
            // console.log(val.rules);
            for (const v of val.rules) {
              v.id = 'l>' + v.id;
            }
            val.option.rules.choices = parse_config_attr(val.option.rules.choices);
            // console.log(val.rules);
          }
        } else if (val.option.type == 'range') {
          if (!think.isEmpty(val.option.rules)) {
            const searchtxt = JSON.parse(val.option.rules).searchtxt;
            const searcharr = [];
            if (!think.isEmpty(searchtxt)) {
              const arr = searchtxt.split(',');
              const len = arr.length;
              for (var i = 0; i < len; i++) {
                const obj = {};
                if (!think.isEmpty(arr[i - 1])) {
                  if (i == 1) {
                    obj.id = 'd>' + arr[i];
                    obj.name = '低于' + arr[i];
                    obj.pid = 0;
                    searcharr.push(obj);
                  } else {
                    obj.id = arr[i - 1] + '>' + arr[i];
                    obj.name = arr[i - 1] + '-' + arr[i];
                    obj.pid = 0;
                    searcharr.push(obj);
                  }
                }
              }
              searcharr.push({id: 'u>' + arr[len - 1], name: '高于' + arr[len - 1], pid: 0});
            }
            // console.log(searcharr);
            val.option.rules = JSON.parse(val.option.rules);
            val.rules = searcharr;
            // val.option.rules.choices = parse_config_attr(val.option.rules.choices);
          }
        }
      }
      console.log(typevar);
      this.assign('typevar', typevar);
    }
    // console.log(sortarr);
    // console.log(!think.isEmpty(sortarr));
    if (!think.isEmpty(sortarr)) {
      // console.log(sortarr);
      sortarr = sortarr.split('|');

      nsobj = {};
      const optionidarr = [];
      const valuearr = [];
      for (const v of sortarr) {
        const qarr = v.split('_');
        nsobj[qarr[0]] = qarr[1];
        if (qarr[1] != 0) {
          const vv = qarr[1].split('>');
          // console.log(vv);
          if (vv[0] == 'd' && !think.isEmpty(vv[1])) {
            map[qarr[0]] = ['<', vv[1]];
          } else if (vv[0] == 'u' && !think.isEmpty(vv[1])) {
            map[qarr[0]] = ['>', vv[1]];
          } else if (vv[0] == 'l' && !think.isEmpty(vv[1])) {
            map[qarr[0]] = ['like', `%"${vv[1]}"%`];
          } else if (!think.isEmpty(vv[0]) && !think.isEmpty(vv[1])) {
            map[qarr[0]] = ['BETWEEN', Number(vv[0]), Number(vv[1])];
          } else {
            if (selectMap[qarr[0]]) {
              let query = '';
              if (qarr[0] == 'xinxileixing') {
                query = qarr[1] == 'x' ? '0' : qarr[1];
              } else {
                const arr = get_id_path(qarr[1]);
                for (const i of arr) {
                  if (selectMap[qarr[0]][i] != '全部') {
                    if (think.isEmpty(query)) {
                      query = selectMap[qarr[0]][i];
                    } else {
                      query += '-' + selectMap[qarr[0]][i];
                    }
                  }
                }
              }
              map[qarr[0]] = ['like', `%${query}%`];
            } else {
              if (qarr[0] == 'diqu') {
                qarr[1] = qarr[1].replace(':', '-');
                this.assign('diqu', qarr[1]);
              }
              map[qarr[0]] = ['like', `%${qarr[1]}%`];
            }
          }
        }
      }
      // where.optionid = ["IN",optionidarr];
      // where['value'] = ["IN",valuearr];
      // let type= await this.model("typeoptionvar").where(where).select();
      //  console.log(type);
      // console.log(map);
    }
    let diqu = this.get('diqu') || '';
    diqu = decodeURI(diqu);
    this.assign('diqu', diqu);
    if (diqu) {
      map.diqu = ['like', `%${diqu}%`];
    }
    let sortQuery = this.get('sortQuery');
    if (sortQuery) {
      sortQuery = JSON.parse(sortQuery);
      sortQuery.jiage = -sortQuery.jiage;
      let arrowClass = '';
      if (sortQuery.jiage == -1) {
        arrowClass = 'oi-arrow-bottom';
        o = {jiage: 'DESC'};
      } else {
        arrowClass = 'oi-arrow-top';
        o = {jiage: 'ASC'};
      }
      this.assign('sortQuery', sortQuery);
      this.assign('arrow', arrowClass);
    } else {
      sortQuery = {jiage: -1};
      o = {jiage: 'DESC'};
      this.assign('sortQuery', sortQuery);
      this.assign('arrow', 'oi-arrow-bottom');
    }
    const data = await this.model(this.mod.name).where(map).page(this.get('page'), num).order(o).countSelect();
    this.assign('page', this.get('page') || '1');

    /* 模板赋值并渲染模板 */
    this.assign('childcategory', {
      shangpingleibie: '物料',
      diqu: '地区'
    });
    this.assign('group_id', group_id);
    this.assign('category', cate);
    this.assign('list', data.data);
    this.assign('totalPages', data.totalPages);
    this.assign('count', data.count);
    this.assign('sort', sort);
    this.assign('nsobj', nsobj);

    this.assign('sortid', sortid);
    // 跨屏
    if (this.isMobile) {
      if (this.isAjax('get')) {
        for (const v of data.data) {
          v.nickname = await get_nickname(v.uid);
          v.create_time = moment(v.create_time).fromNow();
          v.catename = await this.model('category').get_category(v.category_id, 'title');
          v.detail = (v.detail).replace(/<[^>]+>/g, '');
          v.answer_username = await get_nickname(v.answer_users);
          v.update_time = moment(v.update_time).fromNow();
        }

        return this.json(data);
      }
      // console.log(this.mod.name);
      // 手机端模版
      return this.modDisplay('m');
    } else {
      return this.modDisplay();
    }
  }
  /**
   * 信息发布
   * @returns {*}
   */
  async xiadanAction() {
    if (this.isPost) {
      const postData = this.post();
      const loginUser = await this.model('member').where({
        id: this.is_login
      }).find();
      if (postData.yewuleixing == 0) {
        postData.gongid = this.is_login;
        postData.gong_gsmc = loginUser.gsmc;
        postData.gong_username = loginUser.real_name;
        postData.gong_mobile = loginUser.mobile;
        postData.gongqueren = 1;
        postData.xuid = postData.duifangid;
        postData.xu_gsmc = postData.duifanggsmc;
        postData.xu_username = postData.duifangrealname;
        postData.xu_mobile = postData.duifangmobile;
      } else if (postData.yewuleixing == 1) {
        postData.xuid = this.is_login;
        postData.xu_gsmc = loginUser.gsmc;
        postData.xu_username = loginUser.real_name;
        postData.xu_mobile = loginUser.mobile;
        postData.xuqueren = 1;
        postData.gongid = postData.duifangid;
        postData.gong_gsmc = postData.duifanggsmc;
        postData.gong_username = postData.duifangrealname;
        postData.gong_mobile = postData.duifangmobile;
      }
      delete postData.duifangid;
      delete postData.duifanggsmc;
      delete postData.duifangrealname;
      delete postData.duifangmobile;
      if (!postData.hasOwnProperty('mokuaibiaoshi')) {
        postData.mokuaibiaoshi = 0;
      }
      const orderNo = await this.model('cmswing/order').orderid(postData.gongid);
      postData.order_no = orderNo;
      const chuangjianshijian = new Date().toLocaleString();
      postData.chuangjianshijian = chuangjianshijian;
      postData.status = 0;
      const id = await this.model('order').add(postData);
      if (!id) return this.fail('下单失败');
      return this.success({name: '下单成功！'});
    } else {
      if (this.is_login > 0 && this.user.zhucestatus == 2) {
        const { mokuaibiaoshi } = this.get();
        this.assign('mokuaibiaoshi', mokuaibiaoshi);
        this.active = ['/shangping?mokuaibiaoshi=' + mokuaibiaoshi];
        this.meta_title = getxiadantitle(mokuaibiaoshi);
        await this.hook('xinxiUpPics', 'tupian', '', {$hook_key: 'icon'});
        const fengleiRes = await this.model('material').field('id,label,pid').select({where: {status: 1}});
        const fenglei = arr_to_tree(fengleiRes, 0);
        this.assign('fenglei', fenglei);
        return this.modDisplay();
      } else {
        return this.redirect('/');
      }
    }
  }

  // 订单确认
  async querenAction() {
    if (this.isPost) {
      const postData = this.post();
      postData.order_userid = this.is_login;
      if (!think.isEmpty(postData.gongxufabuid)) {
        const gongxufabuInfo = await this.model('gongxufabu').where({
          id: postData.gongxufabuid,
          status: 5
        }).find();
        if (think.isEmpty(gongxufabuInfo)) {
          return this.fail('下单失败');
        }
        postData.info_channel = gongxufabuInfo.info_channel;
        if (['0', '3'].indexOf(postData.yewuleixing) != -1) {
          postData.xuid = postData.loginUserid;
          postData.xu_gsmc = postData.loginUsergsmc;
          postData.xu_username = postData.loginUserrealname;
          postData.xu_mobile = postData.loginUsermobile;
          postData.xuqueren = 1;
          postData.gongid = postData.duifangid;
          postData.gong_gsmc = postData.duifanggsmc;
          postData.gong_username = postData.duifangrealname;
          postData.gong_mobile = postData.duifangmobile;
        } else if (['1', '2'].indexOf(postData.yewuleixing) != -1) {
          postData.gongid = postData.loginUserid;
          postData.gong_gsmc = postData.loginUsergsmc;
          postData.gong_username = postData.loginUserrealname;
          postData.gong_mobile = postData.loginUsermobile;
          postData.gongqueren = 1;
          postData.xuid = postData.duifangid;
          postData.xu_gsmc = postData.duifanggsmc;
          postData.xu_username = postData.duifangrealname;
          postData.xu_mobile = postData.duifangmobile;
        }
      } else {
        const map = {
          0: 1,
          2: 2
        };
        postData.info_channel = map[postData.mokuaibiaoshi];
        if (postData.yewuleixing == 0) {
          postData.gongid = postData.loginUserid;
          postData.gong_gsmc = postData.loginUsergsmc;
          postData.gong_username = postData.loginUserrealname;
          postData.gong_mobile = postData.loginUsermobile;
          postData.gongqueren = 1;
          postData.xuid = postData.duifangid;
          postData.xu_gsmc = postData.duifanggsmc;
          postData.xu_username = postData.duifangrealname;
          postData.xu_mobile = postData.duifangmobile;
        } else if (postData.yewuleixing == 1) {
          postData.xuid = postData.loginUserid;
          postData.xu_gsmc = postData.loginUsergsmc;
          postData.xu_username = postData.loginUserrealname;
          postData.xu_mobile = postData.loginUsermobile;
          postData.xuqueren = 1;
          postData.gongid = postData.duifangid;
          postData.gong_gsmc = postData.duifanggsmc;
          postData.gong_username = postData.duifangrealname;
          postData.gong_mobile = postData.duifangmobile;
        }
      }

      delete postData.duifangid;
      delete postData.duifanggsmc;
      delete postData.duifangrealname;
      delete postData.duifangmobile;
      delete postData.loginUserid;
      delete postData.loginUsergsmc;
      delete postData.loginUserrealname;
      delete postData.loginUsermobile;
      if (!postData.hasOwnProperty('mokuaibiaoshi')) {
        postData.mokuaibiaoshi = 0;
      }

      const orderNo = await this.model('cmswing/order').orderid(postData.gongid);
      postData.order_no = orderNo;
      const chuangjianshijian = new Date().toLocaleString();
      postData.chuangjianshijian = chuangjianshijian;
      postData.status = 0;
      const id = await this.model('order').add(postData);
      if (!id) return this.fail('下单失败');
      if (!think.isEmpty(postData.gongxufabuid)) {
        const res = await this.model('gongxufabu').where({
          id: postData.gongxufabuid
        }).update({
          status: 6
        });
        if (!res) {
          return this.fail('确认挂单失败');
        }
      }
      return this.success({name: '下单成功！'});
    } else {
      const query = this.get();
      if (!think.isEmpty(query.gongxufabuid)) {
        const gongxufabuInfo = await this.model('gongxufabu').where({
          id: query.gongxufabuid
        }).find();
        query.yewuleixing = gongxufabuInfo.xinxileixing;
        delete gongxufabuInfo.xinxileixing;
        Object.assign(query, gongxufabuInfo);
        const duifangInfo = await this.model('member').where({
          id: gongxufabuInfo.faburen
        }).find();

        Object.assign(query, {duifangid: gongxufabuInfo.faburen, duifanggsmc: duifangInfo.gsmc, duifangmobile: duifangInfo.mobile, duifangrealname: duifangInfo.real_name});
      }
      const loginUser = await this.model('member').where({
        id: this.is_login
      }).find();
      this.assign('info', query);
      this.assign('loginUser', loginUser);
      return this.modDisplay();
    }
  }
  // 通过id或mobile查询人员信息
  async charenAction() {
    const query = this.get('query') || this.post('query');
    if (query) {
      const res = await this.model('member').where({
        id: query,
        mobile: query,
        _logic: 'OR'
      }).find();
      if (!res) { return this.fail('查无此人') };
      if (this.is_login == res.id) { return this.fail('不能对自己交易！') };
      const loginUser = await this.model('member').where({
        id: this.is_login
      }).find();
      if (res.zhucestatus != 2) { return this.fail('请添加实名认证成功的会员！') };
      if (loginUser.groupid == res.groupid) { return this.fail('相同身份的会员不能交易！') };
      return this.success(res, '查询成功');
    }
    return this.fail('参数传递错误');
  }
};
